{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "loop-title",
   "metadata": {},
   "source": [
    "# Python 循环控制：while与for的深度解析"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "loop-intro",
   "metadata": {},
   "source": [
    "循环是编程中实现重复执行的核心结构，Python提供了`while`和`for`两种主要循环方式。本文从语法规则、执行流程、适用场景、常见陷阱及最佳实践五个维度展开专业解析。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "while-section",
   "metadata": {},
   "source": [
    "## 一、while循环：条件驱动的重复执行"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "while-syntax",
   "metadata": {},
   "source": [
    "### 1. 核心语法与执行流程\n",
    "```python\n",
    "初始化变量\n",
    "while 条件表达式:\n",
    "    循环体（需缩进）\n",
    "    变量更新（关键防死循环）\n",
    "```\n",
    "执行流程：\n",
    "1. 检查条件表达式，结果为`True`则执行循环体；\n",
    "2. 执行完循环体后再次检查条件；\n",
    "3. 条件为`False`时退出循环。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "while-example",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 示例1：计算1-10的累加和（典型计数循环）\n",
    "total = 0\n",
    "i = 1\n",
    "while i <= 10:\n",
    "    total += i  # 累加当前值\n",
    "    i += 1      # 更新计数器（防死循环关键）\n",
    "print(f'1-10累加和为：{total}')  # 输出：55"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "while-scene",
   "metadata": {},
   "source": [
    "### 2. 适用场景\n",
    "- 未知循环次数（如等待用户输入有效数据）\n",
    "- 需要动态调整循环条件（如实时监控系统）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "while-dynamic",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 示例2：动态条件（等待输入非空字符串）\n",
    "user_input = ''\n",
    "while not user_input.strip():  # 条件：输入为空（包括空格）\n",
    "    user_input = input('请输入有效内容：')\n",
    "print(f'已接收输入：{user_input}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "while-trap",
   "metadata": {},
   "source": [
    "### 3. 常见陷阱与规避\n",
    "- **死循环**：忘记更新条件变量（如遗漏`i += 1`），需在编写时强制检查条件更新逻辑；\n",
    "- **性能问题**：高频条件检查（如`while True`配合`break`），建议优先用`for`遍历可迭代对象。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "for-section",
   "metadata": {},
   "source": [
    "## 二、for循环：迭代驱动的重复执行"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "for-syntax",
   "metadata": {},
   "source": [
    "### 1. 核心语法与执行流程\n",
    "```python\n",
    "for 元素变量 in 可迭代对象:\n",
    "    循环体（需缩进）\n",
    "```\n",
    "执行流程：\n",
    "1. 从可迭代对象中依次取出元素；\n",
    "2. 将元素赋值给`元素变量`并执行循环体；\n",
    "3. 遍历完所有元素后退出循环。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "for-example",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 示例3：遍历列表并计算平均值（典型迭代场景）\n",
    "scores = [85, 92, 78, 90, 88]\n",
    "total = 0\n",
    "for score in scores:  # 直接遍历列表元素\n",
    "    total += score\n",
    "average = total / len(scores)\n",
    "print(f'平均分：{average:.2f}')  # 输出：86.60"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "for-scene",
   "metadata": {},
   "source": [
    "### 2. 适用场景\n",
    "- 已知可迭代对象（如列表、元组、字符串、字典）\n",
    "- 需要访问元素本身（如数据处理、模式匹配）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "for-dict",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 示例4：遍历字典（键值对处理）\n",
    "user_info = {'name':'Alice', 'age':25, 'city':'Beijing'}\n",
    "for key, value in user_info.items():  # 遍历键值对\n",
    "    print(f'{key.capitalize()}: {value}')  # 输出：Name: Alice 等"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "for-trap",
   "metadata": {},
   "source": [
    "### 3. 常见陷阱与规避\n",
    "- **修改迭代对象**：遍历列表时删除/添加元素会导致索引错乱，建议遍历副本（如`for item in list.copy():`）；\n",
    "- **忽略可迭代特性**：误用不可迭代对象（如整数），需确保`in`右侧为可迭代类型（如`range()`生成器）。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "loop-compare",
   "metadata": {},
   "source": [
    "## 三、while与for的对比与选择\n",
    "| 维度        | while循环                  | for循环                    |\n",
    "|-------------|---------------------------|---------------------------|\n",
    "| 驱动方式    | 条件表达式（布尔结果）     | 可迭代对象（元素遍历）     |\n",
    "| 循环次数    | 未知（条件动态变化）       | 已知（可迭代对象长度）     |\n",
    "| 典型场景    | 交互等待、实时监控         | 数据遍历、模式匹配         |\n",
    "| 推荐优先级  | 次选（需谨慎处理条件）     | 首选（结构清晰，减少错误） |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "best-practice",
   "metadata": {},
   "source": [
    "## 四、最佳实践总结\n",
    "1. **优先用for**：当遍历可迭代对象时，`for`比`while`更简洁且不易出错；\n",
    "2. **明确循环终止条件**：`while`必须包含条件更新逻辑，建议在循环开始前初始化变量；\n",
    "3. **避免嵌套过深**：多层循环（如`while`嵌套`for`）会降低可读性，可通过函数封装优化；\n",
    "4. **善用内置函数**：`range()`、`enumerate()`、`zip()`等函数可简化`for`循环写法（示例如下）。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "best-example",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "第1个水果：apple\n",
      "第2个水果：banana\n",
      "第3个水果：cherry\n"
     ]
    }
   ],
   "source": [
    "# 示例5：使用enumerate()获取索引和元素\n",
    "fruits = ['apple', 'banana', 'cherry']\n",
    "for index, fruit in enumerate(fruits, start=1):  # start=1使索引从1开始\n",
    "    print(f'第{index}个水果：{fruit}')  # 输出：第1个水果：apple 等"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "21d933cd",
   "metadata": {},
   "source": [
    "# 九九乘法表\n",
    "## for循环版本"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "c6ac0d04",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1x1= 1 \n",
      "1x2= 2 2x2= 4 \n",
      "1x3= 3 2x3= 6 3x3= 9 \n",
      "1x4= 4 2x4= 8 3x4=12 4x4=16 \n",
      "1x5= 5 2x5=10 3x5=15 4x5=20 5x5=25 \n",
      "1x6= 6 2x6=12 3x6=18 4x6=24 5x6=30 6x6=36 \n",
      "1x7= 7 2x7=14 3x7=21 4x7=28 5x7=35 6x7=42 7x7=49 \n",
      "1x8= 8 2x8=16 3x8=24 4x8=32 5x8=40 6x8=48 7x8=56 8x8=64 \n",
      "1x9= 9 2x9=18 3x9=27 4x9=36 5x9=45 6x9=54 7x9=63 8x9=72 9x9=81 \n"
     ]
    }
   ],
   "source": [
    "\"\"\"\n",
    "在 Python 的 f-string 格式化中， :2 表示将数值格式化为宽度为 2 的字段。\n",
    "具体作用是：若计算结果（ i*j ）的位数小于 2，会在左侧补空格（右对齐），确保输出对齐；\n",
    "若位数等于或超过 2，则直接显示。\n",
    "例如，当 i*j=1 时显示为 1 ， i*j=12 时显示为 12 ，使 99 乘法表的列对齐更整齐。\n",
    "\"\"\"\n",
    "for i in range(1, 10):\n",
    "    for j in range(1, i + 1):\n",
    "        print(f\"{j}x{i}={i * j:2}\", end=' ')\n",
    "    print()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d500b6a7",
   "metadata": {},
   "source": [
    "## while版本"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "807fb8df",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1×1= 1 \n",
      "1×2= 2 2×2= 4 \n",
      "1×3= 3 2×3= 6 3×3= 9 \n",
      "1×4= 4 2×4= 8 3×4=12 4×4=16 \n",
      "1×5= 5 2×5=10 3×5=15 4×5=20 5×5=25 \n",
      "1×6= 6 2×6=12 3×6=18 4×6=24 5×6=30 6×6=36 \n",
      "1×7= 7 2×7=14 3×7=21 4×7=28 5×7=35 6×7=42 7×7=49 \n",
      "1×8= 8 2×8=16 3×8=24 4×8=32 5×8=40 6×8=48 7×8=56 8×8=64 \n",
      "1×9= 9 2×9=18 3×9=27 4×9=36 5×9=45 6×9=54 7×9=63 8×9=72 9×9=81 \n"
     ]
    }
   ],
   "source": [
    "def print_99_table_while():\n",
    "    \"\"\"使用双重while循环打印99乘法表，包含行级注释确保健壮性\"\"\"\n",
    "    row = 1  # 外层循环变量（控制行数）\n",
    "    while row <= 9:  # 外层循环条件：行数不超过9\n",
    "        col = 1  # 内层循环变量（控制列数）\n",
    "        while col <= row:  # 内层循环条件：列数不超过当前行数\n",
    "            # 使用f-string格式化输出，保证结果右对齐占2位，乘法表更整齐\n",
    "            print(f'{col}×{row}={row*col:2}', end=' ')\n",
    "            col += 1  # 内层循环变量更新（防死循环关键）\n",
    "        print()  # 每行结束后换行\n",
    "        row += 1  # 外层循环变量更新（防死循环关键）\n",
    "print_99_table_while()  # 调用函数执行打印"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "95234e96",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
